package logic

import (
	"context"
	"fmt"
	"strconv"

	"server-go/rpc/reward/internal/models"
	"server-go/rpc/reward/internal/svc"
	"server-go/rpc/reward/internal/util"
	"server-go/rpc/reward/types/reward"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminGetDataLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAdminGetDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetDataLogic {
	return &AdminGetDataLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 管理员获取审批列表
func (l *AdminGetDataLogic) AdminGetData(in *reward.AdminGetDataInput) (*reward.AdminGetDataOutput, error) {
	out := &reward.AdminGetDataOutput{Status: 400}
	audit, _ := strconv.ParseInt(in.FormNum, 10, 64)
	tasksDao := &models.TasksDao{Audit: int(audit)}
	taskLs, err := tasksDao.AdminGetDataFind(l.svcCtx.Db)
	if err != nil {
		return out, err
	}
	// 获取发布者姓名
	userIds := []int{}
	for _, v := range taskLs {
		userIds = append(userIds, v.Userid)
	}
	// map[user_id]nick_name
	userMap := make(map[int]*models.UsersDao)
	users, err := (&models.UsersDao{}).FindByIds(l.svcCtx.Db, userIds)
	if err != nil {
		return out, err
	}
	for _, user := range users {
		userMap[user.Id] = user
	}
	// 获取任务类型 map[id]name
	taskTypeMap := make(map[int]string)
	taskTypes, err := (&models.TaskTypeDao{}).Find(l.svcCtx.Db)
	if err != nil {
		return out, err
	}
	for _, v := range taskTypes {
		taskTypeMap[v.Id] = v.Typename
	}
	// 匹配最终数据
	data := []*reward.AdminGetData{}
	for _, v := range taskLs {
		nickName := ""
		email := ""
		if v1, ok := userMap[v.Userid]; ok {
			nickName = v1.Nickname
			email = v1.Email
		}
		typeName := ""
		if v1, ok := taskTypeMap[v.Typeid]; ok {
			typeName = v1
		}
		// 兼容任务创建时间
		startDate := ""
		if v.Createtime != 0 {
			startDate = util.TimeToStrYMDHMS(util.IntToTime(v.Createtime))
		} else {
			startDate = util.TimeToStrYMDHMS(v.CreatedAt)
		}

		data = append(data, &reward.AdminGetData{
			Audit:     fmt.Sprintf("%v", v.Audit),
			Bounty:    uint32(v.Bounty),
			Email:     email,
			Enddate:   v.Enddate,
			Key:       uint32(v.Id),
			Nickname:  nickName,
			Startdate: startDate,
			Taskintro: v.Taskintro,
			Tasktitle: v.Tasktitle,
			TypeName:  typeName,
		})
	}
	out.Status = 200
	out.Data = data
	return out, nil
}
